package com.qiche.util;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.qiche.config.YmlConfig;
import com.qiche.redis.RedisService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * Token : 微信认证access_token获取工具类 从微信API获取access_token并保持到redis中
 *
 * @author zhangds
 * @since 2017-04-19 12:09
 */
@Component
public class Token {
	/*
	 * @Resource private RedisCache redisCache;
	 */
	private Gson gson = new Gson();
	/*@Resource
	private RedisManager redis;*/
	@Autowired
	private RedisService redisService;

	/**
	 * 获取access_token方法 首先读取缓存的信息，如果缓存信息不存在则重新从微信获取新的access_token
	 * 
	 * @return
	 */
	public String get_access_token() {
		String access_token = redisService.get("access_token").toString();
		if (null == access_token || "".equals(access_token)) {
			JsonObject jsonObj = this.getTokenFromWx();
			access_token = jsonObj.get("access_token").getAsString();
			/*redis.setString("access_token", access_token);
			redis.setExpireTime("access_token", 7200);*/
			redisService.set("access_token",access_token,7200L);
		}
		return access_token;
	}

	@Autowired
	private YmlConfig ymlConfig;

	/**
	 * 从微信读取access_token
	 * 
	 * @return
	 */
	private JsonObject getTokenFromWx() {
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + ymlConfig.getWxVerifyAppid() + "&secret="
				+ ymlConfig.getWxVerifySecret();
		String result = HttpUtils.sendGet(url);
		LoggerFactory.getLogger(Token.class).error("---------微信授权结果信息---------");
		LoggerFactory.getLogger(Token.class).error(result);
		JsonObject jsonObject = gson.fromJson(result, JsonObject.class);
		return jsonObject;
	}
}
